package org.zxw.basic.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.zxw.basic.dao.IBaseDao;
import org.zxw.basic.model.Pager;
import org.zxw.basic.model.SystemContext;

public class BaseDaoImpl<T> implements IBaseDao<T> {
	private SessionFactory sessionFactory;
	private Class<?> clz;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Inject
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected Session getSession() {
		return this.sessionFactory.getCurrentSession();
	}

	public Class<?> getClz() {
		if (clz == null) {
			clz = ((Class<?>) (((ParameterizedType) (this.getClass()
					.getGenericSuperclass())).getActualTypeArguments()[0]));
		}
		return clz;
	}

	@Override
	public T add(T t) {
		this.getSession().save(t);
		return t;
	}

	@Override
	public void delete(int id) {
		this.getSession().delete(this.load(id));
	}

	@Override
	public void update(T t) {
		this.getSession().update(t);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T load(int id) {
		return (T) this.getSession().load(getClz(), id);
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public List<T> list(String hql, Object[] args, Map<String, Object> alias) {
		hql = initSort(hql);
		Query query = this.getSession().createQuery(hql);
		setAlias(alias, query);
		setParameter(args, query);
		return query.list();
	}

	private void setParameter(Object[] args, Query query) {
		if (args != null && args.length > 0) {
			int index = 0;
			for (Object arg : args) {
				query.setParameter(index++, arg);
			}
		}
	}

	@SuppressWarnings("rawtypes")
	private void setAlias(Map<String, Object> alias, Query query) {
		if (alias != null) {
			Set<String> keys = alias.keySet();
			for (String key : keys) {
				Object val = alias.get(key);
				if (val instanceof Collection) {
					query.setParameter(key, (Collection) val);
				} else {
					query.setParameter(key, val);
				}
			}
		}
	}

	private String initSort(String hql) {
		String sort = SystemContext.getSort();
		String order = SystemContext.getOrder();
		if (sort != null && !"".equals(sort.trim())) {
			hql += " order by " + sort;
			if (!"desc".equals(order)) {
				hql += " asc";
			} else {
				hql += " desc";
			}
		}
		return hql;
	}

	@Override
	public List<T> list(String hql, Object[] args) {
		return this.list(hql, args, null);
	}

	@Override
	public List<T> list(String hql, Object arg) {
		return this.list(hql, new Object[] { arg });
	}

	@Override
	public List<T> list(String hql) {
		return this.list(hql, null);
	}

	@Override
	public List<T> listByAlias(String hql, Map<String, Object> alias) {
		return this.list(hql, null, alias);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<T> find(String hql, Object[] args, Map<String, Object> alias) {
		hql = initSort(hql);
		String cq = getCountHql(hql, true);
		Query query = this.getSession().createQuery(hql);
		Query cQuery = this.getSession().createQuery(cq);
		setAlias(alias, query);
		setAlias(alias, cQuery);
		setParameter(args, query);
		setParameter(args, cQuery);
		Pager<T> pages = new Pager<T>();
		setPages(query, pages);
		List<T> datas = query.list();
		pages.setDatas(datas);
		long total = (Long) cQuery.uniqueResult();
		pages.setTotal(total);
		return pages;
	}

	@SuppressWarnings("rawtypes")
	private void setPages(Query query, Pager pages) {
		Integer pageSize = SystemContext.getPageSize();
		Integer pageOffset = SystemContext.getPageOffset();
		if (pageSize == null || pageSize < 0) {
			pageSize = 15;
		}
		if (pageOffset == null || pageOffset < 0) {
			pageOffset = 0;
		}
		pages.setOffset(pageOffset);
		pages.setSize(pageSize);
		query.setFirstResult(pageOffset).setMaxResults(pageSize);
	}

	private String getCountHql(String hql, boolean b) {
		String e = hql.substring(hql.indexOf("from"));
		String c = "select count(*) " + e;
		if (b) {
			c.replaceAll("fetch", "");
		}
		return c;
	}

	@Override
	public Pager<T> find(String hql, Object[] args) {
		return this.find(hql, args, null);
	}

	@Override
	public Pager<T> find(String hql, Object arg) {
		return this.find(hql, new Object[] { arg });
	}

	@Override
	public Pager<T> find(String hql) {
		return this.find(hql, null);
	}

	@Override
	public Pager<T> findByAlias(String hql, Map<String, Object> alias) {
		return this.find(hql, null, alias);
	}

	@Override
	public Object queryObject(String hql, Object[] args,
			Map<String, Object> alias) {
		Query query = this.getSession().createQuery(hql);
		setAlias(alias, query);
		setParameter(args, query);
		return query.uniqueResult();
	}

	@Override
	public Object queryObject(String hql, Object[] args) {
		return this.queryObject(hql, args, null);
	}

	@Override
	public Object queryObject(String hql, Object arg) {
		return this.queryObject(hql, new Object[] { arg });
	}

	@Override
	public Object queryObject(String hql) {
		return this.queryObject(hql, null);
	}

	@Override
	public Object queryObjectByAlias(String hql, Map<String, Object> alias) {
		return this.queryObject(hql, null, alias);
	}

	@Override
	public void updateByHql(String hql, Object[] args) {
		Query query = this.getSession().createQuery(hql);
		setParameter(args, query);
		query.executeUpdate();
	}

	@Override
	public void updateByHql(String hql, Object arg) {
		this.updateByHql(hql, new Object[] { arg });
	}

	@Override
	public void updateByHql(String hql) {
		this.updateByHql(hql, null);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <N> List<N> listBySql(String sql, Object[] args,
			Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
		sql = initSort(sql);
		SQLQuery sq = this.getSession().createSQLQuery(sql);
		setAlias(alias, sq);
		setParameter(args, sq);
		if (hasEntity) {
			sq.addEntity(clz);
		} else {
			sq.setResultTransformer(Transformers.aliasToBean(clz));
		}
		return sq.list();
	}

	@Override
	public <N> List<N> listBySql(String sql, Object[] args, Class<?> clz,
			boolean hasEntity) {
		return this.listBySql(sql, args, null, clz, hasEntity);
	}

	@Override
	public <N> List<N> listBySql(String sql, Object arg, Class<?> clz,
			boolean hasEntity) {
		return this.listBySql(sql, new Object[] { arg }, clz, hasEntity);
	}

	@Override
	public <N> List<N> listBySql(String sql, Class<?> clz, boolean hasEntity) {
		return this.listBySql(sql, null, clz, hasEntity);
	}

	@Override
	public <N> List<N> listBySqlAlias(String sql, Map<String, Object> alias,
			Class<?> clz, boolean hasEntity) {
		return this.listBySql(sql, null, alias, clz, hasEntity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <N> Pager<N> findBySql(String sql, Object[] args,
			Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
		sql = initSort(sql);
		String cq = getCountHql(sql, false);
		SQLQuery sq = getSession().createSQLQuery(sql);
		SQLQuery cquery = getSession().createSQLQuery(cq);
		setAlias(alias, sq);
		setAlias(alias, cquery);
		setParameter(args, sq);
		setParameter(args, cquery);
		Pager<N> pages = new Pager<N>();
		setPages(sq, pages);
		if (hasEntity) {
			sq.addEntity(clz);
		} else {
			sq.setResultTransformer(Transformers.aliasToBean(clz));
		}
		List<N> datas = sq.list();
		pages.setDatas(datas);
		long total = ((BigInteger) cquery.uniqueResult()).longValue();
		pages.setTotal(total);
		return pages;
	}

	@Override
	public <N> Pager<N> findBySql(String sql, Object[] args, Class<?> clz,
			boolean hasEntity) {
		return this.findBySql(sql, args, null, clz, hasEntity);
	}

	@Override
	public <N> Pager<N> findBySql(String sql, Object arg, Class<?> clz,
			boolean hasEntity) {
		return this.findBySql(sql, new Object[] { arg }, clz, hasEntity);
	}

	@Override
	public <N> Pager<N> findBySql(String sql, Class<?> clz, boolean hasEntity) {
		return this.findBySql(sql, null, clz, hasEntity);
	}

	@Override
	public <N> Pager<N> findBySqlAlias(String sql, Map<String, Object> alias,
			Class<?> clz, boolean hasEntity) {
		return this.findBySql(sql, null, alias, clz, hasEntity);
	}

}
